"""
日历组件服务层

包含所有与日历和日程相关的业务逻辑：
- CalendarService: 日历管理服务
- EventService: 日程管理服务
- RecurrenceService: 重复规则服务
- ReminderService: 提醒服务
- ShareService: 分享服务
"""

from typing import List, Optional, Dict, Any
from datetime import datetime, timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update, delete, func, and_, or_
from sqlalchemy.orm import selectinload

from ..models import (
    Calendar, Event, EventRecurrence, EventReminder,
    EventParticipant, EventTag, CalendarShare, EventComment
)
from ..schemas import (
    CalendarCreate, CalendarUpdate, EventCreate, EventUpdate,
    EventRecurrenceCreate, EventRecurrenceUpdate, EventReminderCreate, EventReminderUpdate,
    EventParticipantCreate, EventParticipantUpdate, CalendarShareCreate, CalendarShareUpdate,
    EventTagCreate, EventTagUpdate, EventCommentCreate, EventCommentUpdate,
    EventSearchRequest, EventSearchResponse
)


class CalendarService:
    """日历管理服务"""
    
    async def create_calendar(self, db: AsyncSession, calendar: CalendarCreate, owner_id: int) -> Calendar:
        """
        创建日历
        
        Args:
            db: 数据库会话
            calendar: 日历创建数据
            owner_id: 所有者ID
            
        Returns:
            Calendar: 创建的日历
        """
        db_calendar = Calendar(
            **calendar.dict(),
            owner_id=owner_id
        )
        db.add(db_calendar)
        await db.commit()
        await db.refresh(db_calendar)
        return db_calendar
    
    async def get_calendar(self, db: AsyncSession, calendar_id: int, user_id: int) -> Optional[Calendar]:
        """
        获取日历
        
        Args:
            db: 数据库会话
            calendar_id: 日历ID
            user_id: 用户ID
            
        Returns:
            Optional[Calendar]: 日历信息
        """
        query = select(Calendar).where(Calendar.id == calendar_id)
        result = await db.execute(query)
        calendar = result.scalar_one_or_none()
        
        # 检查权限
        if calendar and calendar.owner_id != user_id:
            # 检查是否有分享权限
            share_query = select(CalendarShare).where(
                and_(
                    CalendarShare.calendar_id == calendar_id,
                    CalendarShare.shared_with_id == user_id,
                    CalendarShare.is_accepted == True
                )
            )
            share_result = await db.execute(share_query)
            share = share_result.scalar_one_or_none()
            if not share:
                return None
        
        return calendar
    
    async def get_user_calendars(self, db: AsyncSession, user_id: int) -> List[Calendar]:
        """
        获取用户的日历列表
        
        Args:
            db: 数据库会话
            user_id: 用户ID
            
        Returns:
            List[Calendar]: 日历列表
        """
        # 获取用户拥有的日历
        owned_query = select(Calendar).where(Calendar.owner_id == user_id)
        owned_result = await db.execute(owned_query)
        owned_calendars = owned_result.scalars().all()
        
        # 获取用户被分享的日历
        shared_query = select(Calendar).join(CalendarShare).where(
            and_(
                CalendarShare.shared_with_id == user_id,
                CalendarShare.is_accepted == True
            )
        )
        shared_result = await db.execute(shared_query)
        shared_calendars = shared_result.scalars().all()
        
        return list(owned_calendars) + list(shared_calendars)
    
    async def update_calendar(self, db: AsyncSession, calendar_id: int, calendar: CalendarUpdate, user_id: int) -> Optional[Calendar]:
        """
        更新日历
        
        Args:
            db: 数据库会话
            calendar_id: 日历ID
            calendar: 日历更新数据
            user_id: 用户ID
            
        Returns:
            Optional[Calendar]: 更新后的日历
        """
        # 检查权限
        db_calendar = await self.get_calendar(db, calendar_id, user_id)
        if not db_calendar:
            return None
        
        # 更新数据
        update_data = calendar.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_calendar, field, value)
        
        await db.commit()
        await db.refresh(db_calendar)
        return db_calendar
    
    async def delete_calendar(self, db: AsyncSession, calendar_id: int, user_id: int) -> bool:
        """
        删除日历
        
        Args:
            db: 数据库会话
            calendar_id: 日历ID
            user_id: 用户ID
            
        Returns:
            bool: 是否删除成功
        """
        # 检查权限
        db_calendar = await self.get_calendar(db, calendar_id, user_id)
        if not db_calendar or db_calendar.owner_id != user_id:
            return False
        
        await db.delete(db_calendar)
        await db.commit()
        return True


class EventService:
    """日程管理服务"""
    
    async def create_event(self, db: AsyncSession, event: EventCreate, creator_id: int) -> Event:
        """
        创建日程
        
        Args:
            db: 数据库会话
            event: 日程创建数据
            creator_id: 创建者ID
            
        Returns:
            Event: 创建的日程
        """
        # 检查日历权限
        calendar_service = CalendarService()
        calendar = await calendar_service.get_calendar(db, event.calendar_id, creator_id)
        if not calendar:
            raise ValueError("无权访问此日历")
        
        # 创建日程
        db_event = Event(
            title=event.title,
            description=event.description,
            location=event.location,
            url=event.url,
            start_time=event.start_time,
            end_time=event.end_time,
            all_day=event.all_day,
            timezone=event.timezone,
            status=event.status,
            priority=event.priority,
            visibility=event.visibility,
            busy=event.busy,
            transparent=event.transparent,
            extended_properties=event.extended_properties,
            calendar_id=event.calendar_id,
            creator_id=creator_id
        )
        db.add(db_event)
        await db.commit()
        await db.refresh(db_event)
        
        # 处理标签
        if event.tag_ids:
            await self._add_event_tags(db, db_event.id, event.tag_ids)
        
        # 处理参与者
        if event.participant_emails:
            await self._add_participants(db, db_event.id, event.participant_emails)
        
        # 处理提醒
        if event.reminders:
            await self._add_reminders(db, db_event.id, event.reminders)
        
        return db_event
    
    async def get_event(self, db: AsyncSession, event_id: int, user_id: int) -> Optional[Event]:
        """
        获取日程
        
        Args:
            db: 数据库会话
            event_id: 日程ID
            user_id: 用户ID
            
        Returns:
            Optional[Event]: 日程信息
        """
        query = select(Event).options(
            selectinload(Event.calendar),
            selectinload(Event.tags),
            selectinload(Event.participants),
            selectinload(Event.reminders),
            selectinload(Event.recurrence)
        ).where(Event.id == event_id)
        
        result = await db.execute(query)
        event = result.scalar_one_or_none()
        
        if not event:
            return None
        
        # 检查权限
        if event.creator_id != user_id:
            # 检查日历权限
            calendar_service = CalendarService()
            calendar = await calendar_service.get_calendar(db, event.calendar_id, user_id)
            if not calendar:
                return None
            
            # 检查参与者权限
            participant = await self._get_participant(db, event_id, user_id)
            if not participant:
                return None
        
        return event
    
    async def get_events_by_calendar(self, db: AsyncSession, calendar_id: int, user_id: int) -> List[Event]:
        """
        获取日历下的所有日程
        
        Args:
            db: 数据库会话
            calendar_id: 日历ID
            user_id: 用户ID
            
        Returns:
            List[Event]: 日程列表
        """
        # 检查日历权限
        calendar_service = CalendarService()
        calendar = await calendar_service.get_calendar(db, calendar_id, user_id)
        if not calendar:
            return []
        
        query = select(Event).where(Event.calendar_id == calendar_id)
        result = await db.execute(query)
        return result.scalars().all()
    
    async def update_event(self, db: AsyncSession, event_id: int, event: EventUpdate, user_id: int) -> Optional[Event]:
        """
        更新日程
        
        Args:
            db: 数据库会话
            event_id: 日程ID
            event: 日程更新数据
            user_id: 用户ID
            
        Returns:
            Optional[Event]: 更新后的日程
        """
        # 检查权限
        db_event = await self.get_event(db, event_id, user_id)
        if not db_event:
            return None
        
        # 检查编辑权限
        if db_event.creator_id != user_id:
            participant = await self._get_participant(db, event_id, user_id)
            if not participant or participant.permission.value not in ['edit', 'manage']:
                return None
        
        # 更新数据
        update_data = event.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_event, field, value)
        
        await db.commit()
        await db.refresh(db_event)
        
        # 处理标签更新
        if event.tag_ids is not None:
            await self._update_event_tags(db, event_id, event.tag_ids)
        
        return db_event
    
    async def delete_event(self, db: AsyncSession, event_id: int, user_id: int) -> bool:
        """
        删除日程
        
        Args:
            db: 数据库会话
            event_id: 日程ID
            user_id: 用户ID
            
        Returns:
            bool: 是否删除成功
        """
        # 检查权限
        db_event = await self.get_event(db, event_id, user_id)
        if not db_event:
            return False
        
        # 检查删除权限
        if db_event.creator_id != user_id:
            participant = await self._get_participant(db, event_id, user_id)
            if not participant or participant.permission.value != 'manage':
                return False
        
        await db.delete(db_event)
        await db.commit()
        return True
    
    async def search_events(self, db: AsyncSession, search: EventSearchRequest, user_id: int) -> EventSearchResponse:
        """
        搜索日程
        
        Args:
            db: 数据库会话
            search: 搜索条件
            user_id: 用户ID
            
        Returns:
            EventSearchResponse: 搜索结果
        """
        # 构建查询条件
        query = select(Event).join(Calendar)
        
        # 关键词搜索
        if search.keyword:
            query = query.where(
                or_(
                    Event.title.contains(search.keyword),
                    Event.description.contains(search.keyword),
                    Event.location.contains(search.keyword)
                )
            )
        
        # 时间范围
        if search.start_date:
            query = query.where(Event.start_time >= search.start_date)
        if search.end_date:
            query = query.where(Event.end_time <= search.end_date)
        
        # 日历过滤
        if search.calendar_ids:
            query = query.where(Event.calendar_id.in_(search.calendar_ids))
        
        # 状态过滤
        if search.status:
            query = query.where(Event.status == search.status)
        
        # 优先级过滤
        if search.priority:
            query = query.where(Event.priority == search.priority)
        
        # 创建者过滤
        if search.creator_id:
            query = query.where(Event.creator_id == search.creator_id)
        
        # 权限过滤：只返回用户有权限的日程
        accessible_calendars = await CalendarService().get_user_calendars(db, user_id)
        calendar_ids = [cal.id for cal in accessible_calendars]
        query = query.where(Event.calendar_id.in_(calendar_ids))
        
        # 分页
        offset = (search.page - 1) * search.page_size
        query = query.offset(offset).limit(search.page_size)
        
        # 执行查询
        result = await db.execute(query)
        events = result.scalars().all()
        
        # 获取总数
        count_query = select(func.count(Event.id)).where(query.whereclause)
        count_result = await db.execute(count_query)
        total = count_result.scalar()
        
        return EventSearchResponse(
            events=events,
            total=total,
            page=search.page,
            page_size=search.page_size,
            total_pages=(total + search.page_size - 1) // search.page_size
        )
    
    async def _add_event_tags(self, db: AsyncSession, event_id: int, tag_ids: List[int]) -> None:
        """添加日程标签"""
        # 获取标签
        tag_query = select(EventTag).where(EventTag.id.in_(tag_ids))
        tag_result = await db.execute(tag_query)
        tags = tag_result.scalars().all()
        
        # 添加关联
        event_query = select(Event).where(Event.id == event_id)
        event_result = await db.execute(event_query)
        event = event_result.scalar_one()
        
        for tag in tags:
            event.tags.append(tag)
            # 更新使用次数
            tag.usage_count += 1
        
        await db.commit()
    
    async def _update_event_tags(self, db: AsyncSession, event_id: int, tag_ids: List[int]) -> None:
        """更新日程标签"""
        # 先清除现有标签
        event_query = select(Event).where(Event.id == event_id)
        event_result = await db.execute(event_query)
        event = event_result.scalar_one()
        
        # 减少原标签使用次数
        for tag in event.tags:
            tag.usage_count -= 1
        
        event.tags.clear()
        
        # 添加新标签
        await self._add_event_tags(db, event_id, tag_ids)
    
    async def _add_participants(self, db: AsyncSession, event_id: int, emails: List[str]) -> None:
        """添加参与者"""
        for email in emails:
            participant = EventParticipant(
                event_id=event_id,
                email=email,
                name=email.split('@')[0]  # 简单处理姓名
            )
            db.add(participant)
        await db.commit()
    
    async def _get_participant(self, db: AsyncSession, event_id: int, user_id: int) -> Optional[EventParticipant]:
        """获取参与者"""
        query = select(EventParticipant).where(
            and_(
                EventParticipant.event_id == event_id,
                EventParticipant.user_id == user_id
            )
        )
        result = await db.execute(query)
        return result.scalar_one_or_none()
    
    async def _add_reminders(self, db: AsyncSession, event_id: int, reminders: List[Dict[str, Any]]) -> None:
        """添加提醒"""
        for reminder_data in reminders:
            reminder = EventReminder(
                event_id=event_id,
                **reminder_data
            )
            db.add(reminder)
        await db.commit()


class RecurrenceService:
    """重复规则服务"""
    
    async def create_recurrence(self, db: AsyncSession, event_id: int, recurrence: EventRecurrenceCreate) -> EventRecurrence:
        """
        创建重复规则
        
        Args:
            db: 数据库会话
            event_id: 日程ID
            recurrence: 重复规则数据
            
        Returns:
            EventRecurrence: 创建的重复规则
        """
        db_recurrence = EventRecurrence(
            event_id=event_id,
            **recurrence.dict()
        )
        db.add(db_recurrence)
        await db.commit()
        await db.refresh(db_recurrence)
        return db_recurrence
    
    async def get_recurrence(self, db: AsyncSession, event_id: int) -> Optional[EventRecurrence]:
        """
        获取重复规则
        
        Args:
            db: 数据库会话
            event_id: 日程ID
            
        Returns:
            Optional[EventRecurrence]: 重复规则
        """
        query = select(EventRecurrence).where(EventRecurrence.event_id == event_id)
        result = await db.execute(query)
        return result.scalar_one_or_none()
    
    async def update_recurrence(self, db: AsyncSession, event_id: int, recurrence: EventRecurrenceUpdate) -> Optional[EventRecurrence]:
        """
        更新重复规则
        
        Args:
            db: 数据库会话
            event_id: 日程ID
            recurrence: 重复规则更新数据
            
        Returns:
            Optional[EventRecurrence]: 更新后的重复规则
        """
        db_recurrence = await self.get_recurrence(db, event_id)
        if not db_recurrence:
            return None
        
        # 更新数据
        update_data = recurrence.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_recurrence, field, value)
        
        await db.commit()
        await db.refresh(db_recurrence)
        return db_recurrence
    
    async def delete_recurrence(self, db: AsyncSession, event_id: int) -> bool:
        """
        删除重复规则
        
        Args:
            db: 数据库会话
            event_id: 日程ID
            
        Returns:
            bool: 是否删除成功
        """
        db_recurrence = await self.get_recurrence(db, event_id)
        if not db_recurrence:
            return False
        
        await db.delete(db_recurrence)
        await db.commit()
        return True
    
    async def generate_recurring_events(self, db: AsyncSession, event_id: int, start_date: datetime, end_date: datetime) -> List[datetime]:
        """
        生成重复日程的日期列表
        
        Args:
            db: 数据库会话
            event_id: 日程ID
            start_date: 开始日期
            end_date: 结束日期
            
        Returns:
            List[datetime]: 重复日期列表
        """
        recurrence = await self.get_recurrence(db, event_id)
        if not recurrence:
            return []
        
        # 获取原始日程
        event_query = select(Event).where(Event.id == event_id)
        event_result = await db.execute(event_query)
        event = event_result.scalar_one()
        
        if not event:
            return []
        
        # 生成重复日期
        dates = []
        current_date = event.start_time
        
        while current_date <= end_date:
            # 检查是否符合重复规则
            if self._matches_recurrence_rule(current_date, recurrence):
                # 检查是否在例外日期中
                if not self._is_exception_date(current_date, recurrence):
                    dates.append(current_date)
            
            # 计算下一个日期
            current_date = self._get_next_date(current_date, recurrence)
            
            # 检查结束条件
            if recurrence.end_date and current_date > recurrence.end_date:
                break
            if recurrence.end_count and len(dates) >= recurrence.end_count:
                break
        
        return dates
    
    def _matches_recurrence_rule(self, date: datetime, recurrence: EventRecurrence) -> bool:
        """检查日期是否符合重复规则"""
        if recurrence.repeat_type == RepeatType.DAILY:
            return True
        elif recurrence.repeat_type == RepeatType.WEEKLY:
            if recurrence.repeat_days:
                return date.weekday() in recurrence.repeat_days
            return True
        elif recurrence.repeat_type == RepeatType.MONTHLY:
            if recurrence.repeat_month_day:
                return date.day == recurrence.repeat_month_day
            elif recurrence.repeat_week and recurrence.repeat_week_day:
                # 计算第几个星期几
                week_of_month = (date.day - 1) // 7 + 1
                return date.weekday() == recurrence.repeat_week_day and week_of_month == recurrence.repeat_week
            return False
        elif recurrence.repeat_type == RepeatType.YEARLY:
            if recurrence.repeat_month and recurrence.repeat_month_day:
                return date.month == recurrence.repeat_month and date.day == recurrence.repeat_month_day
            return False
        return False
    
    def _is_exception_date(self, date: datetime, recurrence: EventRecurrence) -> bool:
        """检查是否为例外日期"""
        if not recurrence.exception_dates:
            return False
        
        exception_dates = [
            datetime.fromisoformat(d) if isinstance(d, str) else d
            for d in recurrence.exception_dates
        ]
        
        return date.date() in [d.date() for d in exception_dates]
    
    def _get_next_date(self, date: datetime, recurrence: EventRecurrence) -> datetime:
        """获取下一个日期"""
        if recurrence.repeat_type == RepeatType.DAILY:
            return date + timedelta(days=recurrence.interval)
        elif recurrence.repeat_type == RepeatType.WEEKLY:
            return date + timedelta(weeks=recurrence.interval)
        elif recurrence.repeat_type == RepeatType.MONTHLY:
            return date + timedelta(days=32 * recurrence.interval)  # 简化处理
        elif recurrence.repeat_type == RepeatType.YEARLY:
            return date + timedelta(days=366 * recurrence.interval)  # 简化处理
        return date


class ReminderService:
    """提醒服务"""
    
    async def create_reminder(self, db: AsyncSession, event_id: int, reminder: EventReminderCreate) -> EventReminder:
        """
        创建提醒
        
        Args:
            db: 数据库会话
            event_id: 日程ID
            reminder: 提醒数据
            
        Returns:
            EventReminder: 创建的提醒
        """
        db_reminder = EventReminder(
            event_id=event_id,
            **reminder.dict()
        )
        db.add(db_reminder)
        await db.commit()
        await db.refresh(db_reminder)
        return db_reminder
    
    async def get_reminders(self, db: AsyncSession, event_id: int) -> List[EventReminder]:
        """
        获取日程的所有提醒
        
        Args:
            db: 数据库会话
            event_id: 日程ID
            
        Returns:
            List[EventReminder]: 提醒列表
        """
        query = select(EventReminder).where(EventReminder.event_id == event_id)
        result = await db.execute(query)
        return result.scalars().all()
    
    async def update_reminder(self, db: AsyncSession, reminder_id: int, reminder: EventReminderUpdate) -> Optional[EventReminder]:
        """
        更新提醒
        
        Args:
            db: 数据库会话
            reminder_id: 提醒ID
            reminder: 提醒更新数据
            
        Returns:
            Optional[EventReminder]: 更新后的提醒
        """
        query = select(EventReminder).where(EventReminder.id == reminder_id)
        result = await db.execute(query)
        db_reminder = result.scalar_one_or_none()
        
        if not db_reminder:
            return None
        
        # 更新数据
        update_data = reminder.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_reminder, field, value)
        
        await db.commit()
        await db.refresh(db_reminder)
        return db_reminder
    
    async def delete_reminder(self, db: AsyncSession, reminder_id: int) -> bool:
        """
        删除提醒
        
        Args:
            db: 数据库会话
            reminder_id: 提醒ID
            
        Returns:
            bool: 是否删除成功
        """
        query = select(EventReminder).where(EventReminder.id == reminder_id)
        result = await db.execute(query)
        db_reminder = result.scalar_one_or_none()
        
        if not db_reminder:
            return False
        
        await db.delete(db_reminder)
        await db.commit()
        return True
    
    async def get_pending_reminders(self, db: AsyncSession, current_time: datetime) -> List[EventReminder]:
        """
        获取待发送的提醒
        
        Args:
            db: 数据库会话
            current_time: 当前时间
            
        Returns:
            List[EventReminder]: 待发送的提醒列表
        """
        query = select(EventReminder).join(Event).where(
            and_(
                EventReminder.is_sent == False,
                Event.start_time > current_time
            )
        )
        result = await db.execute(query)
        all_reminders = result.scalars().all()
        
        # 过滤出需要发送的提醒
        pending_reminders = []
        for reminder in all_reminders:
            event_time = reminder.event.start_time
            reminder_time = event_time - timedelta(minutes=reminder.minutes_before)
            
            if current_time >= reminder_time:
                pending_reminders.append(reminder)
        
        return pending_reminders
    
    async def mark_reminder_sent(self, db: AsyncSession, reminder_id: int) -> bool:
        """
        标记提醒为已发送
        
        Args:
            db: 数据库会话
            reminder_id: 提醒ID
            
        Returns:
            bool: 是否标记成功
        """
        query = select(EventReminder).where(EventReminder.id == reminder_id)
        result = await db.execute(query)
        reminder = result.scalar_one_or_none()
        
        if not reminder:
            return False
        
        reminder.is_sent = True
        reminder.sent_at = datetime.utcnow()
        await db.commit()
        return True


class ShareService:
    """分享服务"""
    
    async def share_calendar(self, db: AsyncSession, calendar_id: int, share: CalendarShareCreate, owner_id: int) -> CalendarShare:
        """
        分享日历
        
        Args:
            db: 数据库会话
            calendar_id: 日历ID
            share: 分享数据
            owner_id: 所有者ID
            
        Returns:
            CalendarShare: 分享记录
        """
        # 检查权限
        calendar_service = CalendarService()
        calendar = await calendar_service.get_calendar(db, calendar_id, owner_id)
        if not calendar or calendar.owner_id != owner_id:
            raise ValueError("无权分享此日历")
        
        db_share = CalendarShare(
            calendar_id=calendar_id,
            **share.dict()
        )
        db.add(db_share)
        await db.commit()
        await db.refresh(db_share)
        return db_share
    
    async def get_calendar_shares(self, db: AsyncSession, calendar_id: int, user_id: int) -> List[CalendarShare]:
        """
        获取日历分享列表
        
        Args:
            db: 数据库会话
            calendar_id: 日历ID
            user_id: 用户ID
            
        Returns:
            List[CalendarShare]: 分享列表
        """
        # 检查权限
        calendar_service = CalendarService()
        calendar = await calendar_service.get_calendar(db, calendar_id, user_id)
        if not calendar or calendar.owner_id != user_id:
            return []
        
        query = select(CalendarShare).where(CalendarShare.calendar_id == calendar_id)
        result = await db.execute(query)
        return result.scalars().all()
    
    async def update_share(self, db: AsyncSession, share_id: int, share: CalendarShareUpdate, user_id: int) -> Optional[CalendarShare]:
        """
        更新分享权限
        
        Args:
            db: 数据库会话
            share_id: 分享ID
            share: 分享更新数据
            user_id: 用户ID
            
        Returns:
            Optional[CalendarShare]: 更新后的分享
        """
        query = select(CalendarShare).join(Calendar).where(CalendarShare.id == share_id)
        result = await db.execute(query)
        db_share = result.scalar_one_or_none()
        
        if not db_share or db_share.calendar.owner_id != user_id:
            return None
        
        # 更新数据
        update_data = share.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_share, field, value)
        
        await db.commit()
        await db.refresh(db_share)
        return db_share
    
    async def revoke_share(self, db: AsyncSession, share_id: int, user_id: int) -> bool:
        """
        撤销分享
        
        Args:
            db: 数据库会话
            share_id: 分享ID
            user_id: 用户ID
            
        Returns:
            bool: 是否撤销成功
        """
        query = select(CalendarShare).join(Calendar).where(CalendarShare.id == share_id)
        result = await db.execute(query)
        db_share = result.scalar_one_or_none()
        
        if not db_share or db_share.calendar.owner_id != user_id:
            return False
        
        await db.delete(db_share)
        await db.commit()
        return True
    
    async def accept_share(self, db: AsyncSession, share_id: int, user_id: int) -> bool:
        """
        接受分享
        
        Args:
            db: 数据库会话
            share_id: 分享ID
            user_id: 用户ID
            
        Returns:
            bool: 是否接受成功
        """
        query = select(CalendarShare).where(
            and_(
                CalendarShare.id == share_id,
                CalendarShare.shared_with_id == user_id
            )
        )
        result = await db.execute(query)
        db_share = result.scalar_one_or_none()
        
        if not db_share:
            return False
        
        db_share.is_accepted = True
        db_share.accepted_at = datetime.utcnow()
        await db.commit()
        return True